package com.reading.common.utils;

import java.security.MessageDigest;

/**
 * Md5加密工具
 */
public class Md5Util {

    public enum BitNum {

        Bit16(16, "16位加密"),
        Bit32(32, "32位加密"),;

        private int bitLength;
        private String descr;

        BitNum(int bitLength, String descr) {
            this.bitLength = bitLength;
            this.descr = descr;
        }

        public int getBitLength() {
            return bitLength;
        }
    }

    public static String encrypt(String srcStr, BitNum bitNum) {
        String desStr = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(srcStr.getBytes("UTF-8"));
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }

            switch (bitNum) {
                case Bit16:
                    //16位的加密
                    desStr = buf.toString().substring(8, 24);
                    break;
                case Bit32:
                    //32位的加密
                    desStr = buf.toString();
                    break;
                default:
                    //默认16位加密
                    desStr = buf.toString().substring(8, 24);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return desStr;
    }
}
